import { useRef } from "react";
import { useBoolean } from "ahooks";
import Taro, { useRouter } from "@tarojs/taro";

import Page from "@/components/common/Page";
import ByButton from "@/components/ui/ByButton";
import PopupFormConfirm from "./components/PopupFormConfirm";
import QuestionSetting from "@/packageProject/components/QuestionSetting";

import useFetch from "@/hooks/useFetch";
import ApiAcceptance from "@/api/acceptance";

export default () => {
  const { params } = useRouter();

  const intentCustomerId = Number(params.intentCustomerId);
  const quesNaireId = Number(params.quesNaireId);

  const defultModelRef = useRef({
    intentCustomerId,
    latitude: "",
    longitude: "",
    isCanSee: true,
    quesNaireType: "",
    quesList: [] as any[],
  });

  useFetch(ApiAcceptance.acceptanceTemplateList, {
    defaultParams: [{ intentCustomerId }],
    onSuccess(res: any) {
      const target = res.quesNaireTemplates.find(
        (e) => e.quesNaireId == quesNaireId
      );

      defultModelRef.current = {
        ...defultModelRef.current,
        quesNaireType: target.quesNaireType,
        quesList: [
          {
            ...target,
            quesNaireTempId: target.quesNaireId,
          },
        ],
      };
    },
  });

  const { data } = useFetch<any[]>(ApiAcceptance.acceptanceTemplateDetail, {
    defaultParams: [{ quesNaireId }],
    onAfter: (res: any) => res.quesNaireContent,
  });

  const [visible, { setFalse, setTrue }] = useBoolean();

  const toSubmit = () => {
    // const index = data!.findIndex(
    //   ({ picList }) => !picList || picList?.length === 0
    // );

    // if (index > -1) {
    //   Taro.showToast({ icon: "error", title: `第${index + 1}项未上传图片` });
    //   return;
    // }
    setTrue();
  };

  return (
    <>
      <Page
        footerSticky
        slotFooter={
          <ByButton className="w-2/3" size="large" onClick={toSubmit}>
            提交
          </ByButton>
        }
      >
        {data?.map((item, index) => (
          <QuestionSetting
            source={item}
            index={index + 1}
            key={item.quesNaireId}
          />
        ))}
      </Page>

      {visible && (
        <PopupFormConfirm
          source={data!}
          defultModel={defultModelRef.current}
          onCancel={setFalse}
        />
      )}
    </>
  );
};
